//
//  AppDelegate.m
//  小码哥彩票
//
//  Created by simplyou on 15/11/9.
//  Copyright © 2015年 simplyou. All rights reserved.
//
// 引 JPush功能所需头 件
#define JGPushAPPKey @"cb7a6b38a9d8b89e2d94fbb8"
#import "JPUSHService.h"
// iOS10注册APNs所需头 件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h> 
#endif
// 如果需要使 idfa功能所需要引 的头 件(可选) #import <AdSupport/AdSupport.h>
#import "AppDelegate.h"
#import "XMGRootVc.h"
#import "FMDatabase.h"

#define SQLCMD_CREATE_TABLE_LOTTERY @"CREATE TABLE IF NOT EXISTS lottery(id INTEGER PRIMARY KEY AUTOINCREMENT, ticketType TEXT, date TEXT, numStr TEXT, wager TEXT, prize TEXT)"
//备用表
//主键id 彩票类型 日期／时间 数字字符串 下注多少 中奖与否1中／0否

//投注记录表 / 中奖表
#define SQLCMD_CREATE_TABLE_THROWRECORD @"CREATE TABLE IF NOT EXISTS record(id INTEGER PRIMARY KEY AUTOINCREMENT, ticketType TEXT, date TEXT, numStr TEXT, wager TEXT, prize TEXT)"


FMDatabase *database;
@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate

// 自己的事情自己做, 谁的事情谁管理
// 自定义
/*
 1.自定义控制器: 基本都需要自定义,用于处理复杂的逻辑
 2.自定义控件:当系统的控件不能满足需求的时候需要自定, 还原系统的原有的功能,在增加自己的功能
 3. 自定义模型, 系统没有提供模型,所义需要自定义
*/

// 1.让更多的功能复用, 2,节省公司成本 3.方便多人开发

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 1.创建窗口
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    // 2.1设置窗口的跟控制器
    self.window.rootViewController = [XMGRootVc chooseWindowRootVc];
    
    // 3.让窗口显示
    [self.window makeKeyAndVisible];
    
    //Required
    //notice: 3.0.0及以后版本注册可以这样写,也可以继续 之前的注册 式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加 定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
//    init Push
    // notice: 2.1.5版本的SDK新增的注册 法,改成可上报IDFA,如果没有使 IDFA直接传nil
    // 如需继续使 pushConfig.plist 件声明appKey等配置内容,请依旧使 [JPUSHService setupW
//ithOption:launchOptions] 式初始化。
   [JPUSHService setupWithOption:launchOptions appKey:JGPushAPPKey
                    channel:@"AppStore"
                 apsForProduction:NO
            advertisingIdentifier:nil];
    
    [self openDatabase];
    [self createTable];
    return YES;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger)
                                                               )completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]
        ]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执 这个 法,选择 是否提醒 户,有Badge、Sound、Alert三种类型可以选择设置
}
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(); // 系统要求执 这个 法
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [self closeDatabase];
}

+ (NSString *)pathForDocumentsResource:(NSString *)relativePath
{
    static NSString* documentsPath = nil;
    if (nil == documentsPath)
    {
        NSArray* dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        documentsPath = [dirs objectAtIndex:0];
    }
    return [documentsPath stringByAppendingPathComponent:relativePath];
}

- (void)openDatabase
{
    NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *databaseFilePath = [[documentsPaths objectAtIndex:0] stringByAppendingPathComponent:@"database.sqlite"];
    
    database = [[FMDatabase alloc] initWithPath:databaseFilePath];
    
    if ([database open])
        NSLog(@"open sqlite db ok.");
}

- (void)closeDatabase
{
    if (database != NULL) {
        [database close];
        NSLog(@"close sqlite db ok.");
    }
}

- (void)createTable
{
    if (database != NULL)
    {
        if (![database executeUpdate:SQLCMD_CREATE_TABLE_THROWRECORD]) NSLog(@"Can not create table device");
        if (![database executeUpdate:SQLCMD_CREATE_TABLE_LOTTERY]) NSLog(@"Can not create table snapshot");
    }
}


@end
